package com.slipper.util;

import com.slipper.exception.CommonException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;

import java.io.*;

public class ImageUtil {
    public static String pngToBase64(InputStream inputStream) {
        TranscoderInput transcoderInput = new TranscoderInput(inputStream);
        PNGTranscoder pngTranscoder = new PNGTranscoder();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        TranscoderOutput transcoderOutput = new TranscoderOutput(outputStream);
        try {
            pngTranscoder.transcode(transcoderInput, transcoderOutput);
            byte[] resultBytes = outputStream.toByteArray();
            return java.util.Base64.getEncoder().encodeToString(resultBytes);
        } catch (Exception e) {
            throw new CommonException("图片转换出错！", e);
        }
    }

    public static String imgToBase64(InputStream inputStream) {
        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int read;
            while ((read = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, read);
            }
            byte[] resultBytes = outputStream.toByteArray();
            return java.util.Base64.getEncoder().encodeToString(resultBytes);
        } catch (Exception e) {
            throw new CommonException("图片转换出错！", e);
        }
    }
}
